using System;
using System.Collections.Generic;
using Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer;
using System.Windows.Forms;
using Microsoft.SqlServer.Management.UI.VSIntegration;
using System.Text.RegularExpressions;

namespace SSMS_Scripter
{
    public class TableMenuItem : ToolsMenuItemBase, IWinformsMenuHandler
    {
        public TableMenuItem(string dbName, string tableName, string schemaName)
        {
            SetObjectNames(dbName, tableName, schemaName);
        }
        public string DbName { get; set; }
        public string TableName { get; set; }
        public string SchemaName { get; set; }


        public List<string> GroupByList { get; set; }

        protected override void Invoke()
        {
        }

        /// <summary>
        /// Handles duplication
        /// </summary>
        /// <returns></returns>
        public override object Clone()
        {
            return new TableMenuItem(DbName, TableName, SchemaName);
        }

        public void SetObjectNames(string dbName, string tableName, string schemaName)
        {
            DbName = dbName;
            TableName = tableName;
            SchemaName = schemaName;
        }


        /// <summary>
        /// Returns list of items in context menu
        /// </summary>
        /// <returns></returns>
        public System.Windows.Forms.ToolStripItem[] GetMenuItems()
        {
            ToolStripMenuItem item = new ToolStripMenuItem("Group by...");
            item.Click += new EventHandler(groupBy_Click);
            return new ToolStripItem[] { item };
        }

        void groupBy_Click(object sender, EventArgs e)
        {
            GroupByDialog gbd = new GroupByDialog(this, this.Parent.Connection.ConnectionString, DbName, TableName, SchemaName);
            DialogResult r = gbd.ShowDialog();
            if (r == DialogResult.OK)
            {
                CreateGroupBy(GroupByList);
            }
        }
        public void StoreGroupBy(List<string> result)
        {
            GroupByList = result;
        }
        public void CreateGroupBy(List<string> groupColumns)
        {
            string query = "SELECT\n\t{0},\n\tCOUNT(*) as [Count],\n\t" +
                "CONVERT(decimal(5,2), COUNT(*) * 100. / MAX(t.[Total])) [Pct]\n\nFROM [{1}].[{2}]\n" +
                "CROSS JOIN (SELECT COUNT(*) [Total] FROM [{1}].[{2}]) t\n" +
                "GROUP BY {0}\nORDER BY COUNT(*) DESC";

            string fieldList = "";

            for (int i = 0; i < groupColumns.Count; i++)
            {
                fieldList += string.Format("[{0}]{1}", groupColumns[i], (i < groupColumns.Count - 1 ? ",\n\t" : ""));
            }

            query = string.Format(query, fieldList, SchemaName, TableName);
            Connect.LoadSQLDocument(query);
        }
    }
}
